package com.atguigu.lease.common.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import com.atguigu.lease.model.enums.ItemType;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToItemtypeConverterFactory implements ConverterFactory<String, BaseEnum> {


    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {

        return new Converter<String, T>() {

            @Override
            public T convert(String source) {
                //通过枚举类对象获取枚举对象
                T[] enumConstants = targetType.getEnumConstants();
                //2.遍历枚举数组
                for (T enumConstant : enumConstants) {
                    if(enumConstant.getCode().equals(Integer.valueOf(source))){
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("非法数据");
            }
        };


    }
}
